var prefix = jsctx + "/tenantTicketType";

var tenantTicketType = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        },10)
    };

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listTenantTicketType",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageSize: 20,
                pageList: [20],
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: (params.offset / params.limit) + 1,
                        // mobile: $("#mobile").val().trim()
                    };
                },
                columns: [
                    {
                        field: 'number',
                        title: '#',
                        width: '50', align: 'left',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },

                    {field: 'ticketName', title: '优惠券名称', align: 'left'},
                    {field: 'ticketType', title: '类型', align: 'left'},
                    {field: 'useRequireAmount', title: '使用条件', align: 'left'},
                    {field: 'reducedAmount', title: '优惠', align: 'left'},
                    {field: 'totalTicket', title: '总量', align: 'left'},
                    {field: 'remainTicket', title: '剩余数量', align: 'left'},
                    {field: 'createdTime', title: '创建时间', align: 'left'},
                    {
                        field: 'status',
                        title: '使用状态',
                        width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (row.status == '0') {
                                return '<span class="label label-success">正常</span>';
                            } else if (row.status == '1') {
                                return '<span class="label label-danger">停用</span>';
                            }
                        }
                    },
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        formatter: function (value, row, index) {
                            var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="定时赠送" onclick="tenantTicketType.detialTenantTicketType(\''
                                + row.ticketTypeId
                                + '\')">详情</a> ';


                            var b = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="赠送" onclick="tenantTicketType.giveAway(\''
                                + row.ticketTypeId
                                + '\')">赠送</a> ';

                            if (row.status == '0') {
                                var c = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="tenantTicketType.updateStatus(\''
                                    + row.ticketTypeId
                                    + '\')">停用</a> ';
                            } else if (row.status == '1') {
                                var c = '<a class="btn btn-info btn-sm ' + has_edit + '" href="#" title="桩列表" onclick="tenantTicketType.updateStatus(\''
                                    + row.ticketTypeId
                                    + '\')">启动</a> ';
                            }


                            var d = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="定时赠送" onclick="tenantTicketType.getRecord(\''
                                + row.ticketTypeId
                                + '\')">获取记录</a> ';

                            var e = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="定时赠送" onclick="tenantTicketType.giveRecord(\''
                                + row.ticketTypeId
                                + '\')">赠送记录</a> ';

                            return a + b + c + d + e;

                        }
                    }
                ]
            });
    };

    function addTenantTicketType() {
        location.href = prefix + "/addTenantTicketType";
    }

    function giveAway(ticketTypeId) {
        location.href = prefix + "/giveAway/" + ticketTypeId;
    }

    function timeingGiveAway(ticketTypeId) {
        location.href = prefix + "/timeingGiveAway/" + ticketTypeId;
    }

    function updateStatus(ticketTypeId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'ticketTypeId': ticketTypeId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function giveRecord(ticketTypeId) {
        location.href = prefix + "/giveRecord/" + ticketTypeId;
    }

    function getRecord(ticketTypeId) {
        location.href = prefix + "/getRecord/" + ticketTypeId;
    }

    function detialTenantTicketType(ticketTypeId) {
        location.href = prefix + "/detialTenantTicketType/" + ticketTypeId;
    }

    return {
        init: init,
        reLoad: reLoad,
        updateStatus: updateStatus,
        addTenantTicketType: addTenantTicketType,
        giveAway: giveAway,
        timeingGiveAway: timeingGiveAway,
        getRecord: getRecord,
        giveRecord: giveRecord,
        detialTenantTicketType: detialTenantTicketType

    };
})();


var addTenantTicketType = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    function save() {
        $("#roleIds").val(getCheckedRoles());
        var stationIds = [];
        $(".elecStationId:checked").each(function () {
            stationIds.push($(this).val())
        })
        var stationIds = [];
        $(".elecStationId:checked").each(function () {
            stationIds.push($(this).val())
        })
        $("input[name='layuiTreeCheck']:checked").each(function () {
            if($(this).val()!="undefined"){
                stationIds.push($(this).val())
            }
        })
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/saveOrUpdateTenantTicketType",
            data: $('#frmTenantTicketType').serialize() + "&stationIds=" + stationIds,
            // async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    window.history.back();
                } else {
                    parent.layer.alert(data.message)
                }

            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmTenantTicketType").validate({
            rules: {
                ticketName: {
                    required: true
                },
                gainRequireAmount: {
                    required: true
                },
                totalTicket: {
                    required: true
                }
            },
            messages: {
                ticketName: {
                    required: icon + "请输入优惠券名称"
                },
                gainRequireAmount: {
                    required: icon + "请输入使用条件"
                },
                totalTicket: {
                    required: icon + "请输入发放总数"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }


    layui.use('laydate', function () {
        var laydate = layui.laydate;
        var startTime = laydate.render({
            elem: '#effectStartDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            trigger: 'click',
            done: function (value, dates) {
                endTime.config.min = {
                    year: dates.year,
                    month: dates.month - 1, //关键
                    date: dates.date,
                    hours: 0,
                    minutes: 0,
                    seconds: 0
                };
            }
        });
        var endTime = laydate.render({
            elem: '#effectEndDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            trigger: 'click'
        });

    });


    layui.use(['form', 'jquery','tree', 'util'], function () {
        var form = layui.form;
        var $ = layui.jquery;
        var tree = layui.tree;
        var util = layui.util;
        //点击全选, 勾选---自营
        form.on('checkbox(self_allChoose)', function (data) {
            var child = $(".self_seach input[type='checkbox']");
            child.each(function (index, item) {
                item.checked = data.elem.checked;
            });
            form.render('checkbox');
        });
        //点击全选, 勾选---非自营
        form.on('checkbox(unSelf_allChoose)', function (data) {
            var child = $(".unSelf_seach input[type='checkbox']");
            child.each(function (index, item) {
                item.checked = data.elem.checked;
            });
            form.render('checkbox');
        });
        //点击全选, 勾选---互联互通
        form.on('checkbox(connectivity_allChoose)', function (data) {
            var child = $(".connectivity_seach input[type='checkbox']");
            child.each(function (index, item) {
                item.checked = data.elem.checked;
            });
            form.render('checkbox');
        });
        //点击全选, 勾选---互联互通
        form.on('checkbox(connectivity_inner_checkall)', function (data) {
            var child = $(".connectivity_inner_seach input[type='checkbox']");
            child.each(function (index, item) {
                item.checked = data.elem.checked;
            });
            form.render('checkbox');
        });
        //---自营Li
        form.on("checkbox(self_list)", function (data) {
            $(".self_seach input[type='checkbox']").each(function () {
                if ($(".self_seach input[type='checkbox']:checked").length == $(".self_seach input[type='checkbox']").length) {
                    $('#self_checkall').prop("checked", true)
                } else {
                    $('#self_checkall').prop("checked", false)
                }
            })
            form.render('checkbox');
        });
        //---非自营Li
        form.on("checkbox(unSelf_list)", function (data) {
            $(".unSelf_seach input[type='checkbox']").each(function () {
                if ($(".unSelf_seach input[type='checkbox']:checked").length == $(".unSelf_seach input[type='checkbox']").length) {
                    $('#unSelf_checkall').prop("checked", true)
                } else {
                    $('#unSelf_checkall').prop("checked", false)
                }
            })
            form.render('checkbox');
        });
        //---互联互通外部Li
        form.on("checkbox(connectivity_list)", function (data) {
            $(".connectivity_seach input[type='checkbox']").each(function () {
                if ($(".connectivity_seach input[type='checkbox']:checked").length == $(".connectivity_seach input[type='checkbox']").length) {
                    $('#connectivity_checkall').prop("checked", true)
                } else {
                    $('#connectivity_checkall').prop("checked", false)
                }
            })
            form.render('checkbox');
        });

        //打折与立减切换
        // form.on("radio(discountType)", function (data) {
        //     if ($(this).val() == "0") {
        //         $(".reductionDiv").removeClass("hide");
        //         $(".discountDiv").addClass("hide");
        //     } else {
        //         $(".reductionDiv").addClass("hide");
        //         $(".discountDiv").removeClass("hide");
        //     }
        // });
        //获取后和在日期切换
        // form.on("radio(effectType)", function (data) {
        //     if ($(this).val() == "0") {
        //         $(".gainDiv").removeClass("hide");
        //         $(".dateDiv").addClass("hide");
        //     } else {
        //         $(".gainDiv").addClass("hide");
        //         $(".dateDiv").removeClass("hide");
        //     }
        // });

        //获取互联互通内部桩群
        function listTicketStationHlht() {
            $.ajax({
                cache: false,
                type: "POST",
                url: prefix + "/listTicketStationHlht",
                data: {
                    "ticketTypeId":$("#ticketTypeId").val()
                },
                // processData: false,
                // contentType: false,
                // async: false,
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    console.log(data)
                    var dataList = [];
                    for(var key in data.data){
                        var obj ={
                            title: (data.data[key])[0].tenantName
                            , id: 'undefined'
                            , field: 'tenantName'
                            , checked: false
                            , spread: true
                            , children: data.data[key].map(function (ele) {
                                var childrenObj = {}
                                childrenObj.title = ele.stationName;
                                childrenObj.id = ele.elecStationId;
                                childrenObj.checked = (ele.select=="0"?true:false);
                                // childrenObj.disabled = true;
                                childrenObj.spread = false;
                                return childrenObj
                            })
                        }
                        dataList.push(obj)
                    }
                    //树形组件
                    tree.render({
                        elem: '#connectivity_inner_seach_tree'
                        ,data: dataList
                        ,showCheckbox: true  //是否显示复选框
                        ,id: 'demoId1'
                        ,showLine:true
                        ,isJump: false //是否允许点击节点时弹出新窗口跳转
                        ,click: function(obj){
                            // var data = obj.data;  //获取当前点击的节点数据
                            // layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                            console.log(obj.data)
                        }
                    });
                }
            });
        }
        //获取互联互通外部桩群
        function listTicketStationExternalHlht() {
            $.ajax({
                cache: false,
                type: "POST",
                url: prefix + "/listTicketStationExternalHlht",
                data: {
                    "ticketTypeId": $("#ticketTypeId").val()
                },
                // processData: false,
                // contentType: false,
                // async: false,
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    console.log(data)
                    var dataList = [];
                    for (var key in data.data) {
                        var obj = {
                            title: key
                            , id: 'undefined'
                            , field: 'tenantName'
                            , checked: false
                            , spread: true
                            , children: data.data[key].map(function (ele) {
                                var childrenObj = {}
                                childrenObj.title = ele.stationName;
                                childrenObj.id = ele.elecStationId;
                                childrenObj.checked = (ele.select=="0"?true:false);
                                // childrenObj.disabled = true;
                                childrenObj.spread = false;
                                return childrenObj
                            })
                        }
                        dataList.push(obj)
                    }
                    //树形组件
                    tree.render({
                        elem: '#connectivity_seach_tree'
                        , data: dataList
                        , showCheckbox: true  //是否显示复选框
                        , id: 'demoId1'
                        , showLine: true
                        , isJump: false //是否允许点击节点时弹出新窗口跳转
                        , click: function (obj) {
                            // var data = obj.data;  //获取当前点击的节点数据
                            // layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                            console.log(obj.data)
                        }
                    });
                }
            });
        }
        listTicketStationHlht();
        listTicketStationExternalHlht();
    });


    return {
        init: init
    };
})();

